//
//  DFGridView.m
//  汽车人之家
//
//  Created by HZ on 14-9-30.
//  Copyright (c) 2014年 cn.huiz.gang12. All rights reserved.
//

#import "DFGridView.h"
#import "UIView+DF.h"

@implementation DFGridViewIndexPath

-(instancetype)initWithIndex:(NSInteger)index row:(NSInteger)row column:(NSInteger)column {
    if (self = [super init]) {
         _index = index;
        _row = row;
        _column = column;
       
    }
    return self;
}

+ (instancetype)indexPathWithIndex:(NSInteger)index row:(NSInteger)row column:(NSInteger)column {
     return [[DFGridViewIndexPath alloc] initWithIndex:index row:row column:column];
}



@end

@interface DFGridView() {
    NSMutableArray* _items;
    CGFloat _automaticHeight;
}

@end


@implementation DFGridView


-(NSArray *)items {
    return _items;
}

-(void)reloadData {
 
    NSInteger itemCount = [_dataSource numberOfItemsInGridView:self];
    NSInteger columnCount = [_dataSource numberOfColumnsInGridView:self];
    for (UIView* item in _items) {
        [item removeFromSuperview];
    }
    
    _items = [NSMutableArray arrayWithCapacity:itemCount];
    
    NSInteger row = 0;
    NSInteger column = 0;
    for (int i=0; i<itemCount; i++) {
        row = i / columnCount;
        column = i % columnCount;
        UIView* item = [[UIView alloc] init];
        [_items addObject:item];
        [self addSubview:item];
    }

}


-(void)setDataSource:(id<DFGridViewDataSource>)dataSource {
    _dataSource = dataSource;
    [self reloadData];
}


- (void)layoutSubviews {
    [super layoutSubviews];
    NSInteger itemCount = [_dataSource numberOfItemsInGridView:self];
    NSInteger columnCount = [_dataSource numberOfColumnsInGridView:self];
    NSInteger rowCount = itemCount / columnCount  + itemCount>0?1:0;
    CGFloat itemWidth = self.width / columnCount;
    CGFloat itemHeight= self.height / rowCount;
    UIView* item = nil;
    for (int i=0; i<_items.count; i++) {
        NSInteger column = i % columnCount;
        NSInteger row = i / columnCount;
        item = _items[i];
        item.frame = CGRectMake(column * itemWidth, row * itemHeight, itemWidth, itemHeight);
        [_dataSource gridView:self viewForItem:item atIndexPath:[DFGridViewIndexPath indexPathWithIndex:i row:row column:column]];
        
    }
    
}



-(DFGridViewIndexPath *)indexPathWithItem:(UIView *)item {
    NSInteger columnCount = [_dataSource numberOfColumnsInGridView:self];
    NSInteger i = [_items indexOfObject:item];
    NSInteger row = i / columnCount;
    NSInteger column = i % columnCount;
    return [DFGridViewIndexPath indexPathWithIndex:i row:row column:column];
}


@end
